import {QueryClient, QueryClientProvider} from '@tanstack/react-query'
import {WagmiProvider, useAccount, useConnect, useWriteContract} from 'wagmi'
import {config} from './my/config'
import {useState} from 'react'
import * as React from "react";
import {
    type BaseError,
    useSendTransaction,
    useWaitForTransactionReceipt
} from 'wagmi'
import {abi} from './my/abi'

const queryClient = new QueryClient()


// 根据不同的状态显示不同的文字
const getButtonText = () => {
    const {isConnected} = useAccount()
    if (isConnected) return 'Connected';
    return 'Connect Wallet';
};

function ModernInputWithButtons() {
    const [isFocused, setIsFocused] = useState(false);
    const {connectors, connect} = useConnect()
    const connector = connectors.at(0)
    const tokenAddress = '0xYourTokenContractAddress';
    const tokenABI = [
        {
            "constant": false,
            "inputs": [
                {"name": "_to", "type": "address"},
                {"name": "_value", "type": "uint256"}
            ],
            "name": "transfer",
            "outputs": [{"name": "", "type": "bool"}],
            "type": "function"
        }
    ];
    const {data: hash, isPending, error, writeContract} = useWriteContract()

    const [ready, setReady] = React.useState(false)

    React.useEffect(() => {
        ;(async () => {
            const provider = await connector.getProvider()
            setReady(!!provider)
        })()
    }, [connector])

    async function submit(e: React.FormEvent<HTMLFormElement>) {
        e.preventDefault()
        if (isPending) return; // 防止重复提交
        const formData = new FormData(e.target as HTMLFormElement)
        const to = formData.get('address') as `0x${string}`
        const value = formData.get('value') as string

        writeContract({
            address: to,
            abi,
            functionName: 'mint',
            args: [value as unknown as number],
            chain: undefined,
            account: to
        })
        //sendTransaction({to, value: parseEther(value)})
    }

    const {isLoading: isConfirming, isSuccess: isConfirmed} =
        useWaitForTransactionReceipt({
            hash,
        })

    const inputStyle = {
        width: '100%',
        padding: '10px 15px',
        fontSize: '16px',
        border: `1px solid ${isFocused ? '#4CAF50' : '#ccc'}`,
        borderRadius: '25px',
        outline: 'none',
        backgroundColor: '#f9f9f9',
        color: '#333',
        boxShadow: isFocused ? '0 2px 8px rgba(0, 0, 0, 0.2)' : '0 2px 4px rgba(0, 0, 0, 0.1)',
        transition: 'border-color 0.3s, box-shadow 0.3s',
    };

    const buttonStyle = {
        width: '100%',
        padding: '10px 0',
        fontSize: '16px',
        color: '#fff',
        borderRadius: '25px',
        border: 'none',
        cursor: 'pointer',
        marginTop: '10px',
        transition: 'background-color 0.3s, box-shadow 0.3s',
    };

    const buttonPrimaryStyle = {
        ...buttonStyle,
        backgroundColor: '#4CAF50',
        boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
    };

    const buttonSecondaryStyle = {
        ...buttonStyle,
        backgroundColor: '#008CBA',
        boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)',
    };

    return (
        <div style={{width: '250px', margin: 'auto', textAlign: 'center'}}>
            <form onSubmit={submit}>
                <input
                    name="address"
                    type="text"
                    placeholder="address"
                    style={inputStyle}
                    onFocus={() => setIsFocused(true)}
                    onBlur={() => setIsFocused(false)}
                />
                <input
                    name="value"
                    type="text"
                    placeholder="0.0"
                    style={inputStyle}
                    onFocus={() => setIsFocused(true)}
                    onBlur={() => setIsFocused(false)}
                />
                <button style={buttonPrimaryStyle} disabled={!ready} type="button" onClick={() => connect({connector})}>
                    {getButtonText()}
                </button>

                <button style={buttonSecondaryStyle} type="submit" disabled={isPending}>
                    {isPending ? 'Confirming...' : 'Transfer'}
                </button>
                {hash && <div>Transaction Hash: {hash}</div>}
                {isConfirming && <div>Waiting for confirmation...</div>}
                {isConfirmed && <div>Transaction confirmed.</div>}
                {error && (
                    <div>Error: {(error as BaseError).shortMessage || error.message}</div>
                )}
            </form>
        </div>
    );
}

function App() {

    return (
        <WagmiProvider config={config}>
            <QueryClientProvider client={queryClient}>
                <ModernInputWithButtons/>
            </QueryClientProvider>
        </WagmiProvider>
    )
}

export default App;